package com.example.whereismystuff.classes;

import java.util.ArrayList;
import java.util.Arrays;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.SensorManager;

import java.io.ByteArrayOutputStream;
import java.util.Arrays;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.SensorManager;

public class Database{
	
	private static final String DATABASE_NAME = "Temp Name";
	private static int DATABASE_VERSION = 1, ID = 1;
	private SQLiteDatabase db;
	private DatabaseHelperMain helper;//Temp instance variable. TODO What is context?
	
	public Database(Context context){
		helper = new DatabaseHelperMain(context);
		helper.onCreate(db);
		
		//This snippet gets the latest id from the database and assigns it as an instance
		//variable to the database
		
		Cursor itemsResult = db.rawQuery("SELECT * FROM items WHERE ID = (SELECT MAX(ID) FROM items)", null);
		Cursor usersResult = db.rawQuery("SELECT * FROM users WHERE ID = (SELECT MAX(ID) FROM users)", null);
		
		if(itemsResult.getCount() > 0 && usersResult.getCount() > 0)
		{
			if(itemsResult.getInt(0) >= usersResult.getInt(0))
				ID = itemsResult.getInt(0);
			else
				ID = usersResult.getInt(0);
		}
		else if(itemsResult.getCount() > 0 && usersResult.getCount() == 0)
			ID = itemsResult.getInt(0);
		else if(itemsResult.getCount() == 0 && usersResult.getCount() > 0)
			ID = usersResult.getInt(0);
		//If none of these cases get called, then both tables are empty and the id counter remains at 1
	}//End constructor
	
	public void insertUser(User user){
		
		ContentValues values=new ContentValues(5);
		user.setUniqueID(ID);
		values.put("id", ID++);//Unique ID
		
		values.put("username",user.getUserName());
		values.put("password",user.getPassword());
		values.put("email",user.getEmail());
		
		String tempItems = "";
		ArrayList<Integer> itemList = user.IDList;
		for(int i = 0; i < itemList.size();i++)
			tempItems += itemList.get(i) + " ";
		values.put("items", tempItems);
		
		int tempBool;
		values.put("blocked", tempBool = user.isBlocked()? 1 : 0);
		values.put("isAdmin", tempBool = user.isAdmin()? 1 : 0);
		
		db.insert("users", null, values);
	}//End method
	
	public User getUser(int searchID){
		Cursor cursor = db.query("users", null, " ID=" + ID, null , null, null, null);
		return decodeUser(cursor);
	}
	
	public Item getItem(int searchID){
		//Cursor cursor = db.query("items", null, " ID=" + ID, null , null, null, null);
		return decodeItem(searchID);//return decodeItem(cursor);
	}
	
	public void insertItem(Item item) {	
		ContentValues values=new ContentValues(15);
		
		//item.setID(ID);
		values.put("id", ID++);//Unique ID
		
		int tempInt;//Used to pass in booleans
		
		values.put("isFound", tempInt = item.getIsFound()? 1 : 0);
		values.put("claimed", tempInt = item.getClaimed()? 1 : 0);
		values.put("reward", item.getReward());
		values.put("name",item.getName());
		values.put("description", item.getDescription());
		values.put("city", item.getCity());
		values.put("state", item.getState());
		values.put("zipcode", item.getZipCode());
		
		User tempUser = item.getPoster();
		values.put("posterID", tempInt = item.getPoster() == null ? -1 : item.getPoster().getID());
		tempUser = item.getClaimer();
		values.put("claimerID", tempInt = item.getClaimer() == null ? -1 : item.getClaimer().getID());
		values.put("loc1", item.getLocation()[0]);
		values.put("loc2", item.getLocation()[1]);
		
		//Next few lines convert bitmap to byte[] for storage reasons
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		Bitmap temp = item.getImage();
		temp.compress(Bitmap.CompressFormat.PNG, 100, stream);
		byte[] byteArray = stream.toByteArray();
		values.put("image", byteArray);
		
		String[] tags = item.getTags();
		String tagString = "";
		
		for(int i = 0; i < tags.length; i++)
			tagString += tags[i] + ",";
		
		
		values.put("tags", tagString);
		db.insert("items", null, values);
		//constantsCursor.requery();
	}
	
	private Item decodeItem(int id)
	{
		Item tempItem;
		int itemID;
		boolean itemIsFound;
		boolean itemClaimed;
		int itemReward;
		String itemName;
		String itemDescription;
		String itemCity;
		String itemState;
		int itemZip;
		int itemPosterID;
		int itemClaimerID;
		int[] itemLocation = new int[2];
		Bitmap itemImage;
		String[] itemTags;
		Item item;
		
		byte[] byteArray;
		String tagString;
		String tagTemp;
		ArrayList<String> tags = new ArrayList<String>();
		
		Cursor result = db.query("items", null, " ID=" + ID, null , null, null, null);
		
		itemID = result.getInt(0);
		itemIsFound = (result.getInt(1) == 1);
		itemClaimed = (result.getInt(2) == 1);
		itemReward = result.getInt(3);
		itemName = result.getString(4);
		itemDescription = result.getString(5);
		itemCity = result.getString(6);
		itemState = result.getString(7);
		itemZip = result.getInt(8);
		itemPosterID = result.getInt(9);
		itemClaimerID = result.getInt(10);
		itemLocation[0] = result.getInt(11);
		itemLocation[1] = result.getInt(12);
		
		byteArray = result.getBlob(13);
		itemImage = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
		
		tagString = result.getString(14);
		while(tagString != "")
		{
			int index = tagString.indexOf(',');
			if(index != -1 && tagString != "")
			{
				tagTemp = tagString.substring(0, index);
				tagString = tagString.substring(index + 1);
				tags.add(tagTemp);
			}
			else if ( index == -1 && tagString != "")
			{
				tags.add(tagString.substring(0, tagString.length()));
			}
			else break;
		}
		itemTags = (String[]) tags.toArray();
		
		item = new Item(itemName, itemDescription, itemCity, itemState, itemZip, itemPosterID, itemTags);
		return item;
	}
	
	public User decodeUser(Cursor cursor){
		User tempUser;
		int ID, tempBool;
		String username, password, email, tempItems;
		String[] tempArray;
		boolean blocked, isAdmin;
		ArrayList<Integer> items = new ArrayList<Integer>();
		
		ID = cursor.getInt(0);
		username = cursor.getString(1);
		password = cursor.getString(2);
		email = cursor.getString(3);
		
		tempItems = cursor.getString(4);
		tempArray = tempItems.split(" ");
		for(int i = 0; i < tempArray.length; i++)
			items.add(Integer.parseInt(tempArray[i]));
		
		tempBool = cursor.getInt(5);
		if(tempBool == 0)
			blocked = false;
		else
			blocked = true;
		tempBool = cursor.getInt(6);
		if(tempBool == 0)
			isAdmin = false;
		else
			isAdmin = true;
		
		User user = new User(username, password, email);
		user.IDList = items;
		user.setBlocked(blocked);
		user.setIsAdmin(isAdmin);
		return user;
	}
}//End Database class